import React, { useState, useEffect } from 'react';
import { Button, Toast, Modal } from 'antd-mobile';
import UserAgreement from '../components/UserAgreement.jsx';
import { useAuth } from '../context/AuthContext.jsx';
import { createOrder } from '../server/api';
import { UserContactOutline } from 'antd-mobile-icons';

const plans = [
  {
    code: 'monthly',
    name: '一个月',
    price: '9.9元',
    description: '不满意可退',
    recommended: true,
    save: null,
  },
  {
    code: 'yearly',
    name: '一年',
    price: '19.9元',
    description: '永久免费更新',
    save: '98.9',
  },
  {
    code: 'lifetime',
    name: '永久',
    price: '29.9元',
    description: '24H在线售后',
    save: '178.9',
  },
];

const PlanItem = ({ plan, selected, onClick }) => (
  <div
    onClick={onClick}
    style={{
      border: `1.5px solid ${selected ? '#16C05D' : '#f0f0f0'}`,
      borderRadius: '8px',
      padding: '15px',
      position: 'relative',
      background: selected ? '#f0fff8' : 'white',
      marginBottom: '12px',
      cursor: 'pointer',
    }}
  >
    {plan.recommended && (
      <div
        style={{
          position: 'absolute',
          top: 0,
          right: 0,
          background: '#16C05D',
          color: 'white',
          padding: '2px 6px',
          fontSize: '10px',
          borderTopRightRadius: '8px',
          borderBottomLeftRadius: '8px',
        }}
      >
        推荐
      </div>
    )}
    <div
      style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
      }}
    >
      <div style={{ textAlign: 'left' }}>
        <span style={{ fontWeight: 'bold', fontSize: '16px' }}>
          {plan.name}
        </span>
        <span style={{ margin: '0 8px', color: '#ccc' }}>|</span>
        <span style={{ color: '#888', fontSize: '14px' }}>
          {plan.description}
        </span>
        <div
          style={{
            color: '#e54d42',
            fontWeight: 'bold',
            fontSize: '18px',
            marginTop: '8px',
          }}
        >
          {plan.price}
        </div>
      </div>
      <div
        style={{
          width: '20px',
          height: '20px',
          borderRadius: '50%',
          border: `1.5px solid ${selected ? '#16C05D' : '#ccc'}`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {selected && (
          <div
            style={{
              width: '12px',
              height: '12px',
              borderRadius: '50%',
              background: '#16C05D',
            }}
          ></div>
        )}
      </div>
    </div>
    {plan.save && (
      <div
        style={{
          position: 'absolute',
          bottom: '8px',
          right: '8px',
          background: '#ffeded',
          color: '#e54d42',
          padding: '2px 6px',
          fontSize: '10px',
          borderRadius: '4px',
        }}
      >
        省¥{plan.save}元
      </div>
    )}
  </div>
);

export default function MembershipPage() {
  const [selectedPlan, setSelectedPlan] = useState('monthly');
  const [agreementVisible, setAgreementVisible] = useState(false);

  useEffect(() => {
    if (agreementVisible) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'auto';
    }
    // 组件卸载时恢复 body 滚动
    return () => {
      document.body.style.overflow = 'auto';
    };
  }, [agreementVisible]);
  const { auth } = useAuth();
  const user = auth.userInfo;

  const handlePayment = async () => {
    if (!user) {
      Toast.show({ content: '正在获取用户信息，请稍候...' });
      return;
    }
    try {
      Toast.show({ icon: 'loading', content: '正在创建订单...' });
      const orderResult = await createOrder({
        planCode: selectedPlan,
        userId: user.id,
      });
      if (!orderResult.success) throw new Error(orderResult.message);
      console.log('订单创建成功，下一步调用微信支付', orderResult.data);
      Toast.show({ icon: 'success', content: '订单已创建，等待支付' });
    } catch (error) {
      Toast.show({ icon: 'fail', content: `操作失败: ${error.message}` });
    }
  };

  return (
    <div style={{ background: '#f7f8fa', minHeight: '100vh', padding: '16px' }}>
      <div
        style={{
          background: 'white',
          padding: '20px',
          borderRadius: '12px',
          textAlign: 'center',
        }}
      >
        <h2 style={{ fontSize: '22px', fontWeight: 'bold', margin: '10px 0' }}>
          开通已读功能
        </h2>
        <p style={{ color: '#888', marginBottom: '24px' }}>
          不用再猜，发完立刻知道对方看没看
        </p>

        <div>
          {plans.map((plan) => (
            <PlanItem
              key={plan.code}
              plan={plan}
              selected={selectedPlan === plan.code}
              onClick={() => setSelectedPlan(plan.code)}
            />
          ))}
        </div>

        <Button
          block
          size="large"
          style={{
            marginTop: '20px',
            '--background-color': '#16C05D',
            '--border-color': '#16C05D',
            '--text-color': 'white',
            fontWeight: 'bold',
            fontSize: '16px',
          }}
          onClick={handlePayment}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '8px',
            }}
          >
            <UserContactOutline />
            <span>立即开通</span>
          </div>
        </Button>

        <p style={{ color: '#aaa', fontSize: '12px', marginTop: '15px' }}>
          点击支付即代表您同意
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              setAgreementVisible(true);
            }}
            style={{ color: '#16C05D', textDecoration: 'none' }}
          >
            《用户服务协议》
          </a>
        </p>
        <p style={{ color: '#ccc', fontSize: '12px', marginTop: '20px' }}>
          &lt;&lt;&lt; 兼职赚 🧧 &gt;&gt;&gt;
        </p>
      </div>
      <div
        style={{
          textAlign: 'center',
          color: '#ccc',
          fontSize: '12px',
          padding: '20px 0',
        }}
      >
        微信·版本 8.0.60
      </div>

      <Modal
        visible={agreementVisible}
        title="用户协议"
        style={{ '--width': '90vw' }}
        content={<UserAgreement />}
        closeOnAction
        onClose={() => setAgreementVisible(false)}
        actions={[
          {
            key: 'confirm',
            text: '关闭',
            style: { color: '#16C05D' },
          },
        ]}
      />
    </div>
  );
}
